#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "newform.h"
#include "aboutform.h"
#include "resultform.h"
#include "contentsform.h"
#include "dataform.h"
#include "qtablewidget.h"
#include "pupil.h"

#include <QMdiSubWindow>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    Q_FOREACH (QTabBar* tab, ui->mdiArea->findChildren<QTabBar *>())
    {
        tab->setTabsClosable(true);
        tab->setExpanding(false);
        connect(tab, SIGNAL(tabCloseRequested(int)),
                      this, SLOT(closeMdiTab(int)));
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::closeMdiTab(int i)
{
    QMdiSubWindow *sub = ui->mdiArea->subWindowList()[i];
    sub->close();
}

void MainWindow::openDataForm(QString title, QStringList subjectsList, int objectCount)
{
    DataForm* dataform = new DataForm(this, title, subjectsList, objectCount);
    ui->mdiArea->addSubWindow(dataform);
    dataform->show();

    NewForm* form = (NewForm*)QObject::sender();
    form->parentWidget()->close();
    connect(dataform, SIGNAL(openResultForm(Pupil**, int, QString, QStringList)),
            this, SLOT(openResultForm(Pupil**, int, QString, QStringList)));
}

void MainWindow::openResultForm(Pupil** students, int studentsCount, QString title, QStringList subjectsList)
{
    ResultForm* resultForm = new ResultForm(this, students, studentsCount, title, subjectsList);
    ui->mdiArea->addSubWindow(resultForm);
    resultForm->show();

    NewForm* form = (NewForm*)QObject::sender();
    form->parentWidget()->close();
}

void MainWindow::on_actionNew_triggered()
{
    NewForm* newForm = new NewForm(this);
    connect(newForm, SIGNAL(openDataForm(QString,QStringList,int)),
            this, SLOT(openDataForm(QString,QStringList,int)));

    ui->mdiArea->addSubWindow(newForm);
    newForm->showMaximized();
}

void MainWindow::on_actionAbout_triggered()
{
    AboutForm* about = new AboutForm(this);
    about->show();
}
